<template>
  <div class="user-favorites">
    <h2 class="page-title">我的收藏</h2>
    
    <!-- 收藏列表 -->
    <div v-if="favoriteList.length > 0">
      <el-row :gutter="20">
        <el-col 
          v-for="favorite in favoriteList" 
          :key="favorite.id"
          :xs="24"
          :sm="12"
          :md="8"
        >
          <el-card class="favorite-card" shadow="hover">
            <div class="favorite-image" @click="viewHomestayDetail(favorite.id)">
              <img :src="getHomestayImage(favorite)" :alt="favorite.homestayName" />
              <div class="favorite-price">¥{{ favorite.price }}/晚</div>
            </div>
            
            <div class="favorite-info">
              <h3 class="favorite-name" @click="viewHomestayDetail(favorite.homestayId)">
                {{ favorite.homestayName }}
              </h3>
              
              <p class="favorite-area">
                <i class="el-icon-location"></i> {{ favorite.area }}
              </p>
              
              <div class="favorite-actions">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="viewHomestayDetail(favorite.id)"
                >
                  查看详情
                </el-button>
                
                <el-button 
                  size="small" 
                  type="danger" 
                  plain
                  @click="handleRemoveFavorite(favorite)"
                >
                  取消收藏
                </el-button>
              </div>
              
              <div class="favorite-time">
                收藏时间: {{ favorite.time }}
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 分页 -->
      <div class="pagination-section" v-if="favoriteList.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="totalFavorites"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    
    <!-- 空状态 -->
    <el-empty 
      v-else 
      description="暂无收藏记录" 
      :image-size="200"
    >
      <el-button type="primary" @click="goToHomestayList">浏览民宿</el-button>
    </el-empty>
    
    <!-- 取消收藏确认对话框 -->
    <el-dialog
      title="取消收藏"
      v-model="removeDialogVisible"
      width="400px"
    >
      <p>确定要取消收藏 <strong>{{ currentFavorite?.homestayName }}</strong> 吗？</p>
      
      <template #footer>
        <el-button @click="removeDialogVisible = false">返回</el-button>
        <el-button type="danger" @click="confirmRemoveFavorite" :loading="removeLoading">
          确认取消收藏
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// 移除不需要的导入
// import { ElMessage } from 'element-plus'
// import { favorites as mockFavorites } from '../mock'
// import { favoriteApi } from '../api'
import request from '@/utils/request'
// 路由
const router = useRouter()

// 当前页码
const currentPage = ref(1)
const pageSize = ref(6)
const totalFavorites = ref(0)

// 收藏列表
const favoriteList = ref([])

// 取消收藏相关
const removeDialogVisible = ref(false)
const currentFavorite = ref(null)
const removeLoading = ref(false)

// 获取收藏列表
const fetchFavoriteList = async() => {
      // 构建请求参数
      const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      userId: JSON.parse(localStorage.getItem('user')).id
    }

    // 发送请求获取预约列表
    const res = await request.get('/favorites/page', { params })
    // 处理返回结果
    favoriteList.value = res.data.data.records || [];
    totalFavorites.value = res.data.data.total || favoriteList.value.length
    console.log('预约数据:', favoriteList.value)
  // // 使用模拟数据
  // const data = mockFavorites
  // favoriteList.value = data
  // totalFavorites.value = data.length
}

// 获取民宿图片
const getHomestayImage = (favorite) => {
  // 检查是否有homestayImage字段
  if (favorite.homestayImage) {
    return favorite.homestayImage;
  }
  
  // 检查是否有images数组
  if (Array.isArray(favorite.images) && favorite.images.length > 0) {
    return favorite.images[0];
  }
  
  // 检查是否有img字段
  if (favorite.img) {
    return favorite.img;
  }
  
  // 返回默认图片
  return 'https://picsum.photos/800/600?random=0';
}

// 查看民宿详情
const viewHomestayDetail = (id) => {
  router.push(`/homestay/${id}`)
}

// 处理取消收藏
const handleRemoveFavorite = (favorite) => {
  currentFavorite.value = favorite
  removeDialogVisible.value = true
}

// 确认取消收藏
const confirmRemoveFavorite = async() => {
  if (!currentFavorite.value) return
  
  removeLoading.value = true
  
  const res = await request.post(`/favorites/unCol`, {
      homestayId: currentFavorite.value.id,
      userId: JSON.parse(localStorage.getItem('user')).id
    })
  if (res.data.code === '200') {
    totalFavorites.value = favoriteList.value.length
    alert('已取消收藏')
    fetchFavoriteList()
    removeDialogVisible.value = false
    removeLoading.value = false
  }

}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchFavoriteList()
  window.scrollTo(0, 0)
}

// 每页大小变化处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchFavoriteList()
}

// 跳转到民宿列表
const goToHomestayList = () => {
  router.push('/')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchFavoriteList()
})
</script>

<style scoped>
.user-favorites {
  padding-bottom: 2rem;
}

.page-title {
  margin-top: 0;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.8rem;
}

.favorite-card {
  margin-bottom: 1.5rem;
  transition: transform 0.3s;
}

.favorite-card:hover {
  transform: translateY(-5px);
}

.favorite-image {
  position: relative;
  height: 180px;
  overflow: hidden;
  cursor: pointer;
}

.favorite-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
}

.favorite-price {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 5px 10px;
  font-weight: bold;
}

.favorite-info {
  padding: 15px;
}

.favorite-name {
  margin: 0 0 0.6rem;
  font-size: 1.1rem;
  color: #333;
  cursor: pointer;
}

.favorite-name:hover {
  color: #409eff;
}

.favorite-area {
  color: #666;
  margin-bottom: 1rem;
}

.favorite-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 1rem;
}

.favorite-time {
  font-size: 0.8rem;
  color: #999;
}

.pagination-container {
  text-align: center;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .favorite-image {
    height: 140px;
  }
}
</style> 